package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.BaseConfigBean
import com.glory.cqaospda.bean.WaitMaterialInfoBean
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.PartsModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.google.gson.JsonObject
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_parts.*
import kotlinx.android.synthetic.main.activity_title.*
import java.lang.Exception

class PartsActivity : BaseActivity<PartsModel>(), View.OnClickListener {

    private var Pop: PopWindowsUtils.GeneralPop? = null
    private var namePop: PopWindowsUtils.GeneralPop? = null
    var typeList = ArrayList<String>()
    var nameList = ArrayList<String>()
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@PartsActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun initData() {

        viewModel.defUI.callObserve.observe(this@PartsActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        val waitMaterialInfoBean = it.item as WaitMaterialInfoBean
                        tvType.text = waitMaterialInfoBean.partstype
                        etPartsName.setText(waitMaterialInfoBean.partsname)
                        etComment.setText(waitMaterialInfoBean.comment)
                    }
                    2 -> {
                        etEqpId.setText("")
                        tvType.setText("")
                        etPartsName.setText("")
                        etComment.setText("")
                        etEqpId.requestFocus()
                        viewModel.defUI.toastEvent.value = ToastMessageBean("提交成功", true)
                        finish()
                    }
                    3 -> {
                        typeList.clear()
                        val baseConfigBean = it.item as BaseConfigBean
                        for (item in baseConfigBean.mItemList) {
                            typeList.add(item.mItemValue)
                        }
                    }
                    4 -> {
                        nameList.clear()
                        val baseConfigBean = it.item as BaseConfigBean
                        for (item in baseConfigBean.mItemList) {
                            nameList.add(item.mItemValue)
                        }
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }

        queryEqpData(etEqpId)
        btnParts.setOnClickListener {
            if (Constant.isFastClick()) {
                if (etEqpId.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描设备号", false)
                    return@setOnClickListener
                }
                if (etPartsName.text.toString() == "") {
                    val partsName = if (tvTitle.text.toString() == "待配件") "请输入配件名" else "请输入料号"
                    viewModel.defUI.toastEvent.value = ToastMessageBean(partsName, false)
                    return@setOnClickListener
                }
                if (tvType.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean(
                        if (tvTitle.text.toString() == "待配件") "请选择配件类型" else "请选择待料类型",
                        false
                    )
                    return@setOnClickListener
                }

                val map = JsonObject()
                map.addProperty("EquipmentName", etEqpId.text.toString())
                map.addProperty("WaitMatType", "1")
                map.addProperty(
                    "PartsType",
                    if (tvTitle.text.toString() == "待料") "" else tvType.text.toString()
                )
                map.addProperty(
                    "PartsName",
                    if (tvTitle.text.toString() == "待料") "" else etPartsName.text.toString()
                )
                map.addProperty("Comment", etComment.text.toString())
                viewModel.defaultWaitMaterial(map)
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        lineType.visibility = View.VISIBLE
        tvName.text = "配件名"
        tvTitle.text = "待配件"
        tvTepeName.text = "配件类型"
        tvUserName.text = Constant.UserName
        tvBaseSubmit.visibility = View.GONE
        llParts.visibility = View.GONE
        rbType1.isChecked = true
        rbType2.isChecked = false

        val instance = MyApp.instance
        instance!!.handler = handler
        rbType1.setOnClickListener(this)
        rbType2.setOnClickListener(this)
        FreeApi_ActivityManager.getActivityManager().addActivity(this)
        viewModel.defaultGetBaseConfig()
        viewModel.defaultGetPartsName()
        flType.setOnClickListener {
            if (Pop == null) {
                Pop = PopWindowsUtils.getOneChoosePop(this, flType.width, typeList,
                    ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(string: String, potion: Int) {
                            tvType.text = string
                        }
                    }
                )
            }

            if (Pop!!.isShowing) {
                Pop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivTypeArrow)
                Pop?.showAsDropDown(flType, 0, 0)
            }
        }

        flName.setOnClickListener {
            if (namePop == null) {
                namePop = PopWindowsUtils.getOneChoosePop(this, flName.width, nameList,
                    ivNameArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(string: String, potion: Int) {
                            etPartsName.setText(string)
                        }
                    }
                )
            }

            if (namePop!!.isShowing) {
                namePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivNameArrow)
                namePop?.showAsDropDown(flName, 0, 0)
            }
        }
    }

    override fun layoutId(): Int {
        return R.layout.activity_parts
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.rbType1 -> {
                lineType.visibility = View.VISIBLE
                tvName.text = "配件名"
                tvTitle.text = "待配件"
                tvTepeName.text = "配件类型"
            }
            R.id.rbType2 -> {
                lineType.visibility = View.GONE
                tvName.text = "料号"
                tvTitle.text = "待料"
                tvTepeName.text = "待料类型"
            }
        }
    }

    private fun queryEqpData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            viewModel.defaultEqpInfo(s!!, "1")
        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 520) {
            try {
                val view = window.decorView.findFocus() as EditText
                when (view) {
                    etEqpId -> {
                        etEqpId.setText("")
                        tvType.setText("")
                        etPartsName.setText("")
                        etComment.setText("")
                    }
                    etPartsName -> {
                        etPartsName.setText("")
                    }
                }
            } catch (e: Exception){
                println(e.message)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                108 -> {
                    finish()
                }
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }
}